package com.zwps.biz.domain.tool;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import cn.hutool.core.util.RandomUtil;

public class JwtTool {

    private static final String USER_ID = "uid";

    private static final String TOKEN_PREFIX = "Bearer ";

    private static final String SECRET = "yskj@20230517";

    /**
     * 生成Token
     * 
     * @Title: generateToken
     * @Description:
     * @param uid
     * @return String
     * @author lyh
     * @date 2023年5月17日 上午8:45:21
     */
    public static String generateToken(String uid, String id) {
        return TOKEN_PREFIX + JWT.create().withClaim(USER_ID, uid).withJWTId(id).sign(Algorithm.HMAC256(SECRET));
    }

    public static String generateId(String uid) {
        return System.currentTimeMillis() + "-" + uid + "-" + RandomUtil.randomString(2);
    }

    /**
     * 校验token是否正确
     *
     * @param token  密钥
     * @param secret 用户的密码
     * @return 是否正确
     */
    public static boolean verify(String token, String uid, String secret) {
        try {
            // 根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).withClaim(USER_ID, uid).build();
            // 效验TOKEN
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的uid
     */
    public static String getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(getRawToken(token));
            return jwt.getClaim(USER_ID).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static String getRawToken(String fullToken) {
        if (!fullToken.startsWith(TOKEN_PREFIX)) {
            return fullToken;
        }
        return fullToken.substring(fullToken.indexOf(TOKEN_PREFIX) + TOKEN_PREFIX.length());
    }

    public static String getId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(getRawToken(token));
            return jwt.getId();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

}
